package org.judo.generate.mvc;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.judo.database.JudoDatabaseManager;
import org.judo.menu.Menu;
import org.judo.menu.MenuItem;

public class MenuManipulator
{
	public static void addMenuItem(String menuName,String menuDisplay,String url)
	{
		InputStream is = null;
		
		try
		{
			is =(new JudoDatabaseManager().getClass()).getResourceAsStream(
					"/menus.xml");
			
			SAXBuilder builder = new SAXBuilder();
			Document doc = builder.build(is);
			Element root = doc.getRootElement();
			is.close();
			is = null;
			boolean found = false;
			
			List menus = root.getChildren();
			
			for (int i=0;i<menus.size();i++)
			{
				Element menu = (Element)menus.get(i);
				
				if (!menu.getAttributeValue("name").equals(menuName))
					continue;
				
				List menuItems = menu.getChildren();
				
				for (int y=0;y<menuItems.size();y++)
				{
					Element menuItem = (Element)menuItems.get(y);
					
					if (menuItem.getAttributeValue("display").equals(menuDisplay))
					{
						menuItem.setAttribute("link",url);
						menuItem.setAttribute("logged_out","true");
						menuItem.setAttribute("logged_in","true");
						found = true;
						break;
					}
				}
				
				Element menuItem = new Element("item");
				menu.addContent(menuItem);
				menuItem.setAttribute("display",menuDisplay);
				menuItem.setAttribute("link",url);
				menuItem.setAttribute("logged_out","true");
				menuItem.setAttribute("logged_in","true");
				found = true;
			}
			
			if (!found)
			{
				Element menu = new Element("menu");
				root.addContent(menu);
				menu.setAttribute("name",menuName);
				Element menuItem = new Element("item");
				menu.addContent(menuItem);
				menuItem.setAttribute("display",menuDisplay);
				menuItem.setAttribute("link",url);
				menuItem.setAttribute("logged_out","true");
				menuItem.setAttribute("logged_in","true");
			}
			
			FileOutputStream out = new FileOutputStream("config/runtime/menus.xml");
			XMLOutputter format = new XMLOutputter(Format.getPrettyFormat());
			format.output(doc,out);
			out.flush();	
			out.close();

		}
		catch(Throwable e)
		{
			System.out.println("[FATAL ERROR]: could not load Simple URL mappings because: "+e);
			e.printStackTrace();
		}
		finally
		{
			if (is != null)
			{
				try
				{
					is.close();
				} catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
	}
}
